package com.jingan.nursinghome.regulatory.dialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jingan.nursinghome.regulatory.R;
import com.jingan.nursinghome.regulatory.data.MicrometerTable;
import com.jingan.nursinghome.regulatory.http.Http;
import com.jingan.nursinghome.regulatory.model.User;
import com.jingan.nursinghome.regulatory.select.SelectHome;
import com.jingan.nursinghome.regulatory.select.SelectMain;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.android.support.v7.lib.sin.crown.base.BaseActivity;
import cn.android.support.v7.lib.sin.crown.base.BaseApplication;
import cn.android.support.v7.lib.sin.crown.base.BaseDialog;
import cn.android.support.v7.lib.sin.crown.base.BaseListenner;
import cn.android.support.v7.lib.sin.crown.dialog.ProgressDailog;
import cn.android.support.v7.lib.sin.crown.kotlin.utils.KGsonUtils;
import cn.android.support.v7.lib.sin.crown.utils.AssetsUtils;
import cn.android.support.v7.lib.sin.crown.utils.JSONObjectUtils;
import cn.android.support.v7.lib.sin.crown.utils.UtilAssets;
import cn.android.support.v7.lib.sin.crown.utils.UtilCache;
import cn.android.support.v7.lib.sin.crown.utils.UtilHttp;
import cn.android.support.v7.lib.sin.crown.utils.ProportionUtils;
import cn.android.support.v7.lib.sin.crown.utils.UtilToast;
import cn.android.support.v7.lib.sin.crown.view.SingleChoose;

/**
 * Created by 彭治铭 on 2017/9/27.
 */

public class LoginDialog extends BaseDialog {
    private static LoginDialog loginDialog;
    private BaseListenner mLoginSuccess;

    /**
     * @param activity
     * @param logOrOut     登录还是退出，true登录，false退出登录
     * @param loginSuccess 登录成功，回调。返回为null
     * @return
     */
    public static LoginDialog getInstance(BaseActivity activity, boolean logOrOut, BaseListenner loginSuccess) {
        if (isFinishing(loginDialog)) {
            loginDialog = new LoginDialog(activity);
        } else {
            loginDialog.show();
        }
        if (logOrOut) {
            //登录【只有退出动画，没有显示动画】
            loginDialog.window.setWindowAnimations(R.style.Window_bottom_out);
        } else {
            //退出【退出，显示都有】
            loginDialog.window.setWindowAnimations(cn.android.support.v7.lib.sin.crown.R.style.Crown_Window_bottom);
        }
        loginDialog.baseActivity = activity;
        loginDialog.LogOrOut = logOrOut;
        loginDialog.mLoginSuccess = loginSuccess;
        return loginDialog;
    }

    private long exitTime = 0;

    private LoginDialog(BaseActivity activity) {
        init(activity, R.layout.dialog_login, false, false);
        BaseApplication.getInstance().setStatusBarDrak(window, true);
        //按键屏蔽
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if ((System.currentTimeMillis() - exitTime) > 2000) {
                        baseActivity.SnackbarMake("再按一次退出", true, findViewById(R.id.dialog_login_constraintLayout));
                        exitTime = System.currentTimeMillis();
                    } else {
                        BaseApplication.getInstance().exit();
                    }
                    System.gc();
                    return true;
                }
                return false;
            }
        });

        initUI();
        adapterUI();
    }

    boolean LogOrOut = true;//登录还是退出，true登录，false退出登录
    private String stateMark = "autoLogin";//自动登录标志
    private String userMark = "user";//用户缓存标志, 就只保存一个。所以用户标识就这一个。
    Button btn_login;
    SingleChoose singleChoose;
    EditText password_edit, phone_edit;

    private void initUI() {
        btn_login = (Button) findViewById(R.id.btn_login);
        password_edit = (EditText) findViewById(R.id.password_edit);
        phone_edit = (EditText) findViewById(R.id.phone_edit);
        singleChoose = (SingleChoose) findViewById(R.id.singlechoose_login);
        singleChoose.setTextColor(Color.parseColor("#333333"));
        singleChoose.setMession("自动登录");
        singleChoose.setCancel(true);
        Bitmap general = UtilAssets.getInstance(baseActivity).getBitmapFromAssets(getClass().getName(), "自动登录/square_general.png", 0, true);
        general = ProportionUtils.getInstance().adapterBitmap(general);
        Bitmap selected = UtilAssets.getInstance(baseActivity).getBitmapFromAssets(getClass().getName(), "自动登录/square_selected.png", 0, true);
        selected = ProportionUtils.getInstance().adapterBitmap(selected);
        singleChoose.setBitmap(general, selected);
        singleChoose.setOnStateChangeListener(new BaseListenner<SingleChoose>() {
            @Override
            public void onResult(SingleChoose result) {
                //缓存是否自动登录
                UtilCache.getInstance(baseActivity).put(stateMark, String.valueOf(result.isState()));
            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MicrometerTable.getInstance().getUser().setPhone(phone_edit.getText().toString().trim());
                MicrometerTable.getInstance().getUser().setPassword(password_edit.getText().toString().trim());
                //登录
                onLogin();
            }
        });
        TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {//确定/完成
                    MicrometerTable.getInstance().getUser().setPhone(phone_edit.getText().toString().trim());
                    MicrometerTable.getInstance().getUser().setPassword(password_edit.getText().toString().trim());
                    //登录
                    onLogin();
                    return true;
                }
                return false;
            }
        };
        phone_edit.setOnEditorActionListener(onEditorActionListener);
        password_edit.setOnEditorActionListener(onEditorActionListener);
    }

    private void adapterUI() {
        ProportionUtils.getInstance().adapterScreen(baseActivity, findViewById(R.id.dialog_login_constraintLayout));
        ProportionUtils.getInstance().adapterButton(btn_login);
        ProportionUtils.getInstance().adapterView(findViewById(R.id.line_password));
        ProportionUtils.getInstance().adapterView(findViewById(R.id.line_phone));
        ProportionUtils.getInstance().adapterTextView(password_edit);
        ProportionUtils.getInstance().adapterTextView(phone_edit);
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_login_title));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_login_logo));
        ProportionUtils.getInstance().adapterTextView((TextView) findViewById(R.id.txt_login_logo_content));
        UtilAssets.getInstance(baseActivity).setBackGraound(this.getClass(), findViewById(R.id.phone_icon), "登录/手机.png", 0, true);
        UtilAssets.getInstance(baseActivity).setBackGraound(this.getClass(), findViewById(R.id.password_icon), "登录/密码.png", 0, true);
        ProportionUtils.getInstance().adapterView(findViewById(R.id.bg_top));
    }

    @Override
    protected void listener() {
        if (LogOrOut) {
            String autoLogin = UtilCache.getInstance(baseActivity).getAsString(stateMark);
            if (autoLogin != null) {
                singleChoose.setState(Boolean.valueOf(autoLogin));
            }
            Object object = UtilCache.getInstance(baseActivity).getAsObject(userMark);
            if (object != null && object instanceof User) {
                //获取缓存用户
                MicrometerTable.getInstance().setUser((User) object);
                //自动填写用户名和密码
                phone_edit.setText(MicrometerTable.getInstance().getUser().getAccount().trim());
                password_edit.setText(MicrometerTable.getInstance().getUser().getPassword().trim());
                if (singleChoose.isState() && MicrometerTable.getInstance().getUser().getState().trim().equals("1")) {
                    //自动登录
                    user(MicrometerTable.getInstance().getUser());//根据角色进行跳转
                    if (mLoginSuccess != null) {
                        mLoginSuccess.onResult(null);
                    }
                }
            }
        } else {
            //退出登录
            MicrometerTable.getInstance().getUser().setState("0");
            UtilCache.getInstance(baseActivity).put(userMark, MicrometerTable.getInstance().getUser());
        }
    }

    String error;//错误信息

    //true验证通过，false验证失败
    private boolean validation() {
        if ((MicrometerTable.getInstance().getUser().getPhone().trim().equals("")) && (MicrometerTable.getInstance().getUser().getPassword().trim().equals(""))) {
            error = "账号和密码不能为空";
            return false;
        }
        if (MicrometerTable.getInstance().getUser().getPhone().trim().equals("")) {
            error = "账号不能为空";
            return false;
        }
        if (MicrometerTable.getInstance().getUser().getPassword().trim().equals("")) {
            error = "密码不能为空";
            return false;
        }
//        if (MicrometerTable.getInstance().getUser().getPhone().trim().length() < 11) {
//            error = "手机号格式不正确";
//            return false;
//        }
//        if (MicrometerTable.getInstance().getUser().getPassword().trim().length() < 6) {
//            error = "密码不能小于6位数";
//            return false;
//        }
        //验证通过
        error = "success";
        return true;
    }

    ProgressDailog progressDailog;//登陆进度条

    //登录
    private void onLogin() {

        if (validation()) {

            if (progressDailog == null) {
                progressDailog = ProgressDailog.getInstance(baseActivity);
            } else {
                progressDailog.show();
            }

            Http.getInstance().Login(MicrometerTable.getInstance().getUser().getPhone().trim(), MicrometerTable.getInstance().getUser().getPassword().trim(), new UtilHttp.RequestCallBack() {
                @Override
                public boolean onStart() {
                    return false;
                }

                @Override
                public void onSuccess(String result) {
                    //Log.e("test", "登陆返回:\t" + result);
                    //{"code":10001,"errmsg":"invalid code"}
                    try {

                        if (progressDailog != null) {
                            progressDailog.dismiss();
                        }

                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code").toString().trim();
                        if (code.equals("0")) {
                            JSONArray jsonArray = jsonObject.getJSONArray("list");
                            JSONObject jsonObject2 = jsonArray.getJSONObject(0);
//                            MicrometerTable.getInstance().getUser().setId(jsonObject2.getString("id"));
//                            MicrometerTable.getInstance().getUser().setUtype(jsonObject2.getString("utype"));
                            //Log.e("test","用户ID:\t"+MicrometerTable.getInstance().getUser().getId());
                            MicrometerTable.getInstance().setUser((User) JSONObjectUtils.getInstance().getBean(jsonObject2, User.class));
                            //登陆成功
                            //缓存用户账户
                            UtilCache.getInstance(baseActivity).put(MicrometerTable.getInstance().getUser().getPhone().trim(), MicrometerTable.getInstance().getUser().getPassword().trim());

                            //登录成功
                            MicrometerTable.getInstance().getUser().setState("1");
                            user(MicrometerTable.getInstance().getUser());//根据角色进行跳转
                            //缓存用户【会覆盖之前的用户,只会保存一个】
                            UtilCache.getInstance(baseActivity).put(userMark, MicrometerTable.getInstance().getUser());
                            if (mLoginSuccess != null) {
                                mLoginSuccess.onResult(null);
                            }
                        } else {
                            //登陆失败
                            String errmsg = jsonObject.getString("errmsg");
                            baseActivity.SnackbarMake(errmsg, true, findViewById(R.id.dialog_login_constraintLayout));
                        }
                    } catch (JSONException e) {
                        Log.e("test", "登陆json数据解析异常:\t" + e.getMessage());
                    }
                }

                @Override
                public void onFailure(String result) {

                    if (progressDailog != null) {
                        progressDailog.dismiss();
                    }

                    String pwd = UtilCache.getInstance(baseActivity).getAsString(MicrometerTable.getInstance().getUser().getPhone().trim());
                    if (pwd != null && pwd.trim().equals(MicrometerTable.getInstance().getUser().getPassword().trim())) {
                        //登录成功
                        MicrometerTable.getInstance().getUser().setState("1");
                        user(MicrometerTable.getInstance().getUser());//根据角色进行跳转
                        //Log.e("test","用户ID2:\t"+MicrometerTable.getInstance().getUser().getId());
                        //缓存用户【会覆盖之前的用户,只会保存一个】
                        UtilCache.getInstance(baseActivity).put(userMark, MicrometerTable.getInstance().getUser());
                        if (mLoginSuccess != null) {
                            mLoginSuccess.onResult(null);
                        }
                    } else {
                        if (result.contains("No address associated with hostname") || result.contains("No address") || result.contains("with hostname")) {
                            baseActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    UtilToast.showToastView("没有网络");
                                }
                            });
                        } else {
                            baseActivity.SnackbarMake("用户名或密码错误", true, findViewById(R.id.dialog_login_constraintLayout));
                        }
                    }
                }
            });
        } else {
            //登录失败
            baseActivity.SnackbarMake(error, true, findViewById(R.id.dialog_login_constraintLayout));
        }
    }

    //根据角色进行跳转
    private void user(User user) {
        //用户类型 1巡检用户 user1 123
        //2巡检机构用户 3总巡检机构用户 zonyi 123
        //4为组长 5为组员 fk11     123    组长；fk12   123   组员
        String utype = user.getUtype().trim();
        //Log.e("test","用户类型:\t"+utype);
        if (utype.equals("1")) {
            LoginDialog.this.dismiss();//巡检用户
        } else if (utype.equals("2") || utype.equals("3")) {
            //跳转到企业端
            baseActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SelectMain(baseActivity, true, true).show();
                    LoginDialog.this.dismiss();//巡检用户
                }
            });
        } else if (utype.equals("4") || utype.equals("5")) {
            //跳转到分开巡检
            LoginDialog.this.dismiss();
        }


    }

    @Override
    protected void recycleView() {

    }
}
